package interfaz;

import clases.ClsDatabase;
import clases.ClsException;
import clases.ClsMetodos;
import clases.renderIcono;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author SER
 */
public class dlgPresupuestoPrecio extends javax.swing.JDialog {

    private ClsMetodos metodos = new ClsMetodos();
    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboIndice = new DefaultComboBoxModel();
    String id_proyecto = "1";
    int tipo = 1;
    String cod_sub = "";
    String nombre_sub = "";
//    String idString=null;
    /**
     * Creates new form dlgInsumos2
     *
     * @param parent
     * @param modal
     */
    int c1, c2;

    public dlgPresupuestoPrecio(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        _iniciar();//Iniciamos algunos componentes por defecto...

    }

    public dlgPresupuestoPrecio(java.awt.Frame parent, boolean modal, String id, int tipo_d, String cod_sub_d, String nombre_d) {
        super(parent, modal);
        initComponents();

        id_proyecto = id;
        tipo = tipo_d;
        cod_sub = cod_sub_d;
        nombre_sub = nombre_d;
        _iniciar();//Iniciamos algunos componentes por defecto...
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public final void _iniciar() {
        setLocationRelativeTo(null);
        metodos._iconJDialog(this);
        alinear_tabla();
        txtBuscar.setText("");
        txtBuscar.requestFocus();
        c1 = 0;
        c2 = 0;
        metodos.comboboxLlenarMas(cboTipoInsumo, modelCboTipoInsumo, "SELECT idinsumo_tipo,nombre FROM insumo_tipo");
        metodos.comboboxLlenarMas(cboIndice, modelCboIndice, "SELECT idinsumo_indice,concat(idinsumo_indice,'-',descripcion) FROM insumo_indice");
        _cargarDatosTable();

        c1 = 1;
        c2 = 1;
        tblInsumos.setDefaultRenderer(Object.class, new renderIcono());
        metodos.tablaLongitudColumnas(tblInsumos, new int[]{0, 15, 25, 460, 40, 80, 80, 80, 0, 0});
        metodos.tablaOcultarcolumnas(tblInsumos, new int[]{0, 8, 9});
        tblInsumos.getColumnModel().getColumn(6).setCellEditor(new clases.ClsCellEditorInsumoPrecio(bd, 1, this));
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void alinear_tabla() {
        //izquierda
        DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
        modelocentrar.setHorizontalAlignment(SwingConstants.RIGHT);
        tblInsumos.getColumnModel().getColumn(5).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(6).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(7).setCellRenderer(modelocentrar);
    }

    public void seleccionar_base(String valor) {
        metodos.seleccionar_tabla(tblInsumos, 0, valor);
    }

    public void _cargarDatosTable() {
        String like = "";
        if (tipo == 1) {
            like = "";
        } else {
            like = cod_sub;
            setTitle(getTitle() + " - Sub Presupuesto: " + nombre_sub);
        }
        String nombreBuscar = txtBuscar.getText().toString();//,sum(partida_detalle.`precio_parcial`)
        String sql = "", sql2 = "";
        //insumo_tipo.`abreviatura`
        sql = " insumo.`idinsumo`,'',insumo_tipo.`idinsumo_tipo` ,insumo.`nombre` ,unidad.`simbolo`,"
                + "sum(partida_detalle.`cantidad`) ,insumo.`precio` ,sum(partida_detalle.`cantidad`)*insumo.`precio`,"
                + " insumo_indice.`descripcion`,insumo_tipo.`idinsumo_tipo`";
        sql2 = "FROM "
                + "     `partida_detalle` partida_detalle INNER JOIN `insumo` insumo ON partida_detalle.`idinsumo` = insumo.`idinsumo`\n"
                + "     INNER JOIN `unidad` unidad ON insumo.`idunidad` = unidad.`idunidad`\n"
                + "     INNER JOIN `insumo_tipo` insumo_tipo ON insumo.`idinsumo_tipo` = insumo_tipo.`idinsumo_tipo`\n"
                + "     INNER JOIN `insumo_indice` insumo_indice ON insumo.`idinsumo_indice` = insumo_indice.`idinsumo_indice`\n"
                + "WHERE\n"
                + "     partida_detalle.idproyecto = '" + id_proyecto + "' and partida_detalle.idpresupuesto like '%" + like + "'  and insumo.nombre like '%" + nombreBuscar + "%'  and insumo.idinsumo_tipo like '" + modelCboTipoInsumo.getElementAt(cboTipoInsumo.getSelectedIndex()) + "%'  "
                + "and insumo_indice.idinsumo_indice like '" + modelCboIndice.getElementAt(cboIndice.getSelectedIndex()) + "%' "
                + "GROUP BY insumo.`idinsumo`,insumo.`nombre` ,	unidad.`simbolo`,"
                + "insumo.`precio` ,"
                + " insumo_indice.`descripcion`,insumo_tipo.`idinsumo_tipo`"
                + "ORDER BY\n"
                + "     insumo_tipo.`orden` ASC,\n"
                + "     insumo.`nombre` ASC";
        tablaLlenaSql_defecto(tblInsumos, sql, sql2);
        metodos.tablaRedondea(tblInsumos, new int[]{5, 6, 7});
        metodos.tablaNumeracion(tblInsumos, new int[]{1});
        iconos_tipo_insumo(tblInsumos, 9, 2);
        //quitar_eyh(tblInsumos);
    }

    public boolean tablaLlenaSql_defecto(javax.swing.JTable table, String camposSelect, String sqlFromWhere) {
        DefaultTableModel mdt = (DefaultTableModel) table.getModel();
        metodos.tablaLimpia(mdt);
        boolean va = true;
        String sql = "SELECT " + camposSelect + " " + sqlFromWhere;
        int n = 0;
        try {
            bd.getConnection();
            PreparedStatement pstm = bd.conn.prepareStatement(sql);
            ResultSet res = pstm.executeQuery();

            //Previene que en camposSelect tenga: * o concat(   -->para obtener el numero de columnas
//            if (camposSelect.trim().equals("*") || camposSelect.toLowerCase().indexOf("concat(") != -1) {
            ResultSetMetaData rsmd = res.getMetaData();
            n = rsmd.getColumnCount();
//            } else {
//                String colname[] = camposSelect.split(",");
//                n = colname.length;
//            }
//            System.err.println("n-Result-getColumnCount: "+String.valueOf(n));

            while (res.next()) {

                Object mat[] = new Object[n];
                for (int i = 0; i < n; i++) {
                    mat[i] = res.getString(i + 1);
                }
                if (mat[4].toString().equals("%mo") == false) {
                    mdt.addRow(mat);
                }

            }
            res.close();
        } catch (Exception e) {
            System.err.println("sql: " + e);
            e.printStackTrace();
            ClsException._exceptionWriteFile(e, "tablaLlenaSql");
        }

        //System.out.println("tablaLlenaSql--> " + sql);
        return va;
    }

    public void quitar_eyh(javax.swing.JTable tbl) {
        DefaultTableModel mdt = (DefaultTableModel) tbl.getModel();
        int n = mdt.getRowCount();
        for (int i = 0; i < n; i++) {
            if (mdt.getValueAt(i, 4).toString().equals("%mo")) {
                mdt.removeRow(i);
            }
        }
    }

    public void calculo_parcial(Object valor) {
        int fila = tblInsumos.getSelectedRow();
        if (fila != -1) {
            double cant = Double.parseDouble(tblInsumos.getValueAt(fila, 5).toString());
            double pre = Double.parseDouble(valor.toString());
            double tot = cant * pre;
            tblInsumos.setValueAt(metodos.redondeo_2(tot), fila, 7);
        }

    }

    public void iconos_tipo_insumo(javax.swing.JTable tabla, int col_tipo, int col_asigna) {
        ImageIcon icon1 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_obrero.png"));
        ImageIcon icon3 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_herramienta_12.png"));
        ImageIcon icon4 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_servicios.png"));
        int n = tabla.getRowCount();
        for (int i = 0; i < n; i++) {
            String valor = tabla.getValueAt(i, col_tipo).toString();
            if (valor.equals("1")) {
                tabla.setValueAt(new JLabel(icon1), i, col_asigna);
            } else if (valor.equals("2")) {
                tabla.setValueAt(new JLabel(icon2), i, col_asigna);
            } else if (valor.equals("3")) {
                tabla.setValueAt(new JLabel(icon3), i, col_asigna);
            } else if (valor.equals("4")) {
                tabla.setValueAt(new JLabel(icon4), i, col_asigna);
            } else {
                tabla.setValueAt(new JLabel(icon3), i, col_asigna);
            }
        }
    }
    //___________________________________________________________________________________ Soy una barra separadora :)

    public void EliminarInsumo() {
        int fila = tblInsumos.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila != -1) {
            //Confirmamos la eliminacion
            if (JOptionPane.showConfirmDialog(null, "Está seguro que desea eliminar el Insumo seleccionado", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id = tblInsumos.getValueAt(fila, 0).toString();
                boolean seRepite = bd.verif_repite("SELECT idinsumo FROM partida_detalle WHERE idinsumo='" + id + "'");
                if (!seRepite) {
                    seRepite = bd.verif_repite("SELECT idinsumo FROM partida_base_detalle WHERE idinsumo='" + id + "'");
                    if (!seRepite) {
                        boolean seElimino = bd.delete("insumo", "idinsumo='" + id + "'");
                        if (seElimino) {
                            _cargarDatosTable();
                            //JOptionPane.showMessageDialog(null, "Se elimino el Insumo con exito");
                        }
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "No se puede eliminar este Insumo porque ya está siendo utilizado");
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Seleccione un Insumo");
        }
    }
//___________________________________________________________________________________ Soy una barra separadora :)

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlInsumos = new javax.swing.JPanel();
        pnlTablaInsumo = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtBuscar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cboIndice = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        cboTipoInsumo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Precios Insumos");
        setResizable(false);

        pnlTablaInsumo.setBackground(new java.awt.Color(225, 235, 247));
        pnlTablaInsumo.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Cód.", "N°", "", "Descripción", "Unidad", "Cantidad", "P. Unitario", "P. Parcial", "Índice", "idtipo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, true, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInsumos.setRowHeight(23);
        tblInsumos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblInsumos.getTableHeader().setReorderingAllowed(false);
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tblInsumos);

        pnlTablaInsumo.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 95, 938, 400));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(846, 506, 102, -1));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        jPanel1.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(67, 27, 270, -1));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Nombre:");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(16, 27, -1, 25));

        cboIndice.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboIndice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboIndiceActionPerformed(evt);
            }
        });
        jPanel1.add(cboIndice, new org.netbeans.lib.awtextra.AbsoluteConstraints(711, 27, 210, -1));

        jLabel11.setText("Índice unificado:");
        jPanel1.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(611, 30, 90, -1));

        cboTipoInsumo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTipoInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoInsumoActionPerformed(evt);
            }
        });
        jPanel1.add(cboTipoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 27, 170, -1));

        jLabel9.setText("Tipo insumo:");
        jPanel1.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(355, 30, -1, -1));

        pnlTablaInsumo.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 930, 70));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pnlTablaInsumo.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 330));

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/partida_lista.png"))); // NOI18N
        jButton2.setText("Ir a partida");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        pnlTablaInsumo.add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 510, 120, -1));

        javax.swing.GroupLayout pnlInsumosLayout = new javax.swing.GroupLayout(pnlInsumos);
        pnlInsumos.setLayout(pnlInsumosLayout);
        pnlInsumosLayout.setHorizontalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlInsumosLayout.createSequentialGroup()
                .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 969, Short.MAX_VALUE)
                .addGap(2, 2, 2))
        );
        pnlInsumosLayout.setVerticalGroup(
            pnlInsumosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlTablaInsumo, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlInsumos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked
    }//GEN-LAST:event_tblInsumosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        _cargarDatosTable();
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cboTipoInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoInsumoActionPerformed
        if (c1 == 1) {
            _cargarDatosTable();
        }
    }//GEN-LAST:event_cboTipoInsumoActionPerformed

    private void cboIndiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboIndiceActionPerformed
        if (c1 == 1) {
            _cargarDatosTable();
        }
    }//GEN-LAST:event_cboIndiceActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int fila = tblInsumos.getSelectedRow();
        if (fila != -1) {
            String idinsumo=tblInsumos.getValueAt(fila,0 ).toString();
            dlgPartidasLista dialog = new dlgPartidasLista(this, true,id_proyecto,idinsumo);
            dialog.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "Seleccione un Insumo");
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgPresupuestoPrecio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgPresupuestoPrecio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgPresupuestoPrecio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgPresupuestoPrecio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgPresupuestoPrecio dialog = new dlgPresupuestoPrecio(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboIndice;
    private javax.swing.JComboBox cboTipoInsumo;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane3;
    public javax.swing.JPanel pnlInsumos;
    private javax.swing.JPanel pnlTablaInsumo;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
